<template>
    <div>
        <!-- 卡片视图 -->
        <el-card shadow="always">
            <!-- 面包屑导航 -->
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>公司内部</el-breadcrumb-item>
                <el-breadcrumb-item>用户列表</el-breadcrumb-item>
            </el-breadcrumb>

            <el-tabs v-model="activeName" type="border-card">
                <el-tab-pane label="在职" name="1">
                    <!-- 添加用户 -->
                    <el-button type="primary" style="margin-bottom:20px;" @click="showadduser">添加新用户</el-button>
                    <!-- 数据列表 -->

                    <el-table :data="tableData" border style="width: 100%">
                        <el-table-column type="index" label="#" width="80"></el-table-column>
                        <el-table-column prop="name" label="姓名" width="120"></el-table-column>
                        <el-table-column prop="nickname" label="昵称" width="150"></el-table-column>
                        <el-table-column prop="phone" label="手机号" width="180"></el-table-column>
                        <el-table-column prop="groups_title" label="所属组"></el-table-column>
                        <el-table-column label="操作" width="245">
                            <template slot-scope="scope">
                              <el-tooltip class="item" effect="dark" content="离职" placement="top" :enterable="false">
                                  <el-button size="mini" type="danger" @click="examineBtn(scope.row)">
                                      <i class="iconfont icon-lizhi" style="margin:0 auto"></i>
                                  </el-button>
                              </el-tooltip>

                              <el-tooltip class="item" effect="dark" content="设置权限" placement="top" :enterable="false">
                                  <el-button size="mini" type="warning" @click="setRights(scope.row)">
                                      <i class="el-icon-setting" style="margin:0 auto"></i>
                                  </el-button>
                              </el-tooltip>

                              <el-tooltip class="item" effect="dark" content="设置用户组" placement="top" :enterable="false">
                                  <el-button size="mini" type="success" @click="setGroup(scope.row)">
                                      <i class="iconfont icon-user-group" style="margin:0 auto" ></i>
                                  </el-button>
                              </el-tooltip>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="离职" name="2">
                    <!-- 数据列表 -->
                    <el-table :data="tableData" border style="width: 100%">
                        <el-table-column type="index" label="#"  width="80"></el-table-column>
                        <el-table-column prop="name" label="姓名" width="120"></el-table-column>
                        <el-table-column prop="nickname" label="昵称" width="150"></el-table-column>
                        <el-table-column prop="phone" label="手机号" width="180"></el-table-column>
                        <el-table-column prop="groups_title" label="所属组"></el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>

            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryInfo.p"
              :page-sizes="[10, 20, 50, 80]"
              :page-size="queryInfo.limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="count"
            ></el-pagination>
        </el-card>

        <!-- 分配权限弹窗-->
        <el-dialog title="设置权限" :visible.sync="dialogVisible" width="70%">
            <el-tree
              :data="treeData"
              show-checkbox
              node-key="id"
              :default-expanded-keys="defaultKeys"
              :default-checked-keys="defaultKeys"
              :props="defaultProps"
              ref="treeRef"
            ></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="commitRightsBtn">确定</el-button>
            </span>
        </el-dialog>

        <!-- 设置用户组-->
        <el-dialog title="设置用户组" :visible.sync="GroupDialogVisible" width="50%">
            <div style="margin-top: 20px">
                <el-radio-group v-model="radioGroup2" size="small">
                   <el-radio :label="item.id" border v-for="item in checkboxGroup1" :key="item.id">{{ item.title }}</el-radio>
                </el-radio-group>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="GroupDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="setRightBtn">确定</el-button>
            </span>
        </el-dialog>

        <!-- 添加新用户对话框 -->
        <el-dialog
          title="添加新用户"
          :visible.sync="addUserDialogVisible"
          width="35%"
          :show-close="Flag"
          :close-on-press-escape="Flag"
          :close-on-click-modal="Flag"
          @close="closeDialog"
        >
            <el-form label-width="100px" ref="AddFormRef" @submit.native.prevent>
                <el-form-item label="手机号" prop="telInput" required>
                    <input type="text" class="input_" placeholder="手机号" @change="inputChagne" v-model="registerForm.telInput">
                </el-form-item>
                <el-form-item label="姓名" prop="name" required>
                    <input type="text" class="input_" placeholder="姓名" @change="inputChagne" v-model="registerForm.name">
                </el-form-item>
                
                <el-form-item label="用户组" v-model="seloptions" prop="groups">
                    <el-select v-model="seloptions" v-if="options.length>0" required placeholder="请选择">
                        <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.title"
                        :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <!-- <span style="color:red;font-size:14px;margin:20px 0" v-if="addType === 1" @>Tip:请复制下面链接进行注册</span> -->
            <span id="listenUrl">{{ urlValue }}</span>
              <span slot="footer" class="dialog-footer">
                <el-button @click="addUserDialogVisible = false" :disabled="cancelBtn">取 消</el-button>
                <el-button type="primary" @click="addUser" :disabled="addBtn">添加</el-button>
            </span>
        </el-dialog>

        
    </div>
</template>

<script>
import {get} from "../../../../public/API/query";
import config from "../../../../public/config";

// 自定义手机号规则
export default {
    data() {
        var checkMobile = (rule, value, callback) => {
            const regMobile = /^1[345678]\d{9}$/;
            if (regMobile.test(value)) {
                return callback();
            }
            // 返回一个错误提示
            callback(new Error("请输入合法的手机号码"));
        };
        return {
            //添加时选择的用户组选项
            options:[],
            seloptions:'',
            //列表数据
            tableData: [],
            //查询参数
            queryInfo: {
                p: 1,
                limit: 10,
                type: 1,
            },
            //总条数
            count: null,
            //设置权限弹窗开关
            dialogVisible: false,
            currentPage4: 1,
            searchData1: "",
            searchData2: "",
            defaultProps: {
                children: "_child",
                label: "title",
            },
            treeData: [],
            activeName: "1",
            //审核弹窗开关
            ExamineDialogVisible: false,
            radio: 1,
            //设置用户组开关
            GroupDialogVisible: false,
            checkboxGroup1: [],
            radioGroup2: "",
            defaultKeys: [],
            userId: "",
            registerForm: {
                telInput: "",
                name:"",
            },
            //添加用户对话框开关
            addUserDialogVisible: false,
            //添加之后显示的url
            urlValue: "",
            //添加用户返回type
            addType: "",
            Flag: false,
            AddFormRule: {
                telInput: [
                    { required: true, message: "请输入手机号码", trigger: "blur" },
                    { validator: checkMobile, trigger: "blur", required: true },
                ],
            },
            cancelBtn: false,
            addBtn: false,
        };
    },
    methods: {
        //获取权限树
        setRights(value) {
            this.userId = value.id;
            this.dialogVisible = true;

            get(`company/usersList/powerPage`,{ id: value.id },(res) => {
                this.treeData = res.data.list;
                this.defaultKeys = [];
                var that = this;
                (function getTree(data) {
                    for (const i in data) {
                        if (!data[i]._child && data[i].isCheck == "1") {
                            that.defaultKeys.push(data[i].id);
                        } else {
                            getTree(data[i]._child);
                        }
                    }
                })(this.treeData);
            });
        },
        //获取列表数据
        getTableData() {
            get(`company/usersList/index`,{
                    p: this.queryInfo.p,
                    limit: this.queryInfo.limit,
                    type: this.activeName,
                },res=>{
                    this.tableData = res.data._list;
                    this.count = res.data.count;
                }
            );
          
        },
        handleSizeChange(newSize) {
            this.queryInfo.limit = newSize;
            this.getTableData();
        },
        handleCurrentChange(newPage) {
            this.queryInfo.p = newPage;
            this.getTableData();
        },
        //离职按钮
        examineBtn(value) {
            this.$confirm("是否要进行离职操作", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(()=>{
                get(`company/usersList/leave`,{
                    id: value.id,
                },res=>{
                    if (res.code == 200) {
                        this.$message.success("离职操作成功！");
                        this.getTableData();
                    } else if (res.code == 301) {
                        this.$message.error(res.data);
                    } else {
                        this.$message.error("设置失败");
                    }
                })
            }).catch(()=>{
                this.$message.info("已取消操作")
            })
        },
        //设置用户组按钮
        setGroup(value) {
            this.GroupDialogVisible = true;
            this.userId = value.id;
            get(`company/group/index`,this.queryInfo,res=>{
                this.checkboxGroup1 = res.data._list.filter(item=>{
                        return item.status == 2
                });
            });
        },
        checkBox(value) {
            console.log(value);
        },
        //设置用户组 提交权限
        setRightBtn() {
            get("company/usersList/setGroup", {
                    id: this.userId,
                    group_id: this.radioGroup2,
                },(res) => {
                if (res.code == 200) {
                    this.GroupDialogVisible = false;
                    this.$message.success(res.data)
                    this.getTableData()
                }else{
                    this.$message.error(res.data)
                }
            });
        },
        showadduser(){
            this.registerForm.name = ''
            this.registerForm.telInput = ''
            this.seloptions = ''
            get('company/usersList/addPage',{},res=>{
                this.addUserDialogVisible = true
                this.options = res.data
            })
        },
        //添加用户
        addUser() {
              get(`company/usersList/addSub`,{
                      tel: this.registerForm.telInput,
                      groups_id:this.seloptions,
                      name:this.registerForm.name
                  },res=>{
                    this.addUserDialogVisible = false
                    this.getTableData()
                    if (res.code==200) {
                        return this.$message.success("成功")
                    }
                    // if (res.data.type == 1) {
                    //     this.addType = res.data.type;
                    //     this.urlValue = res.data.data;
                    //     this.cancelBtn = true;
                    //     this.addBtn = true;
                    //     this.Flag = false;
                    //     const url = document.getElementById("listenUrl");
                    //     url.oncopy = function(e) {
                    //         _self.$message.success("复制成功");
                    //         if (e.target.textContent === _self.urlValue) {
                    //             _self.Flag = true;
                    //             _self.cancelBtn = false;
                    //         }
                    //     };
                        
                    // }else {
                    //     this.addType = "";
                    //     this.urlValue = "";
                    //     this.Flag = true;
                    //     return this.$message.error(res.data);
                    // }
                });
        },
        inputChagne() {
            this.addBtn = false;
            this.addType = "";
            this.urlValue = "";
        },
        closeDialog() {
            this.addBtn = false;
            this.addType = "";
            this.urlValue = "";
            this.registerForm.telInput = "";
            this.Flag = true;
        },
        //提交权限
        commitRightsBtn() {
            const keys = [
              ...this.$refs.treeRef.getCheckedKeys(),
              ...this.$refs.treeRef.getHalfCheckedKeys(),
            ];
            var newArr = [];
            (function delMax(arr, data) {
                for (const i in data) {
                    var hasId = arr.findIndex((item) => {
                        return item == data[i].id;
                    });
                    if (hasId != -1 && !data[i]._child) {
                        newArr.push(arr[hasId]);
                    } else {
                        delMax(arr, data[i]._child);
                    }
                }
            })(keys, this.treeData);

            const idStr = newArr.join(",");
            get(`company/usersList/submitPower`,{
                    id: this.userId,
                    menuIds: idStr,
                },res=>{
                    if (res.code == 200) {
                        this.$message.success("设置权限成功");
                        this.dialogVisible = false;
                    } else {
                        this.$message.error(res.data);
                    }
                }
            );
        },
        // //搜索功能
        // async searchBtn(title, type) {
        //   this.isDisabled = true;
        //   const { data: res } = await this.$axios.get(
        //     config.get("app_url") + `/company/usersList/index`,
        //     {
        //       params: {
        //         token: this.queryInfo.token,
        //         title,
        //         type: this.activeName,
        //       },
        //     }
        //   );
        //   this.count = res.data.count;
        //   this.tableData = res.data._list;
        // },
    },
    watch: {
        activeName: function() {
            this.queryInfo.p = 1;
            this.getTableData();
        },
    },
    created() {
        this.getTableData();
        
    }
}
</script>

<style lang="less" scoped>
.el-breadcrumb {
    margin-bottom: 30px;
}
.el-pagination {
    margin-top: 30px;
}
.addRulesWrap {
    margin-left: 80px;
}
.addRules {
    position: absolute;
    right: 25%;
    bottom: 5%;
}
.disable {
    margin-left: 15px;
}
.dialog-content {
    margin-left: 60px;
}
</style>
